package cn.yunhe.service.impl;

import cn.yunhe.dao.RedPackageDao;
import cn.yunhe.dao.UserRedPackageDao;
import cn.yunhe.model.RedPacket;
import cn.yunhe.model.UserRedPacket;
import cn.yunhe.service.UserRedPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by zs on 2018/1/5.
 */
@Service
public class UserRedPackageServiceImpl implements UserRedPackageService {

    @Autowired
    private UserRedPackageDao userRedPackageDao = null;

    @Autowired
    private RedPackageDao redPackageDao = null;

    //失败
    private static final int FAILED = 0;

    public int grapRedPackage(Long redPackageId, Long userId) {
        //获得红包信息
        RedPacket redPacket = redPackageDao.getRedPacketForUpdate(redPackageId);
        //当前小红包库存大于0
        if (redPacket.getStock() > 0) {
            redPackageDao.decreaseRedPackage(redPackageId);
            //生成抢红包信息
            UserRedPacket userRedPacket = new UserRedPacket();
            userRedPacket.setRedPacketId(redPackageId);
            userRedPacket.setUserId(userId);
            userRedPacket.setAmount(redPacket.getUnitAmount());
            userRedPacket.setNote("抢红包" + redPackageId);
            //插入抢红包信息
            int result = userRedPackageDao.grapRedPackage(userRedPacket);
            return result;
        }
        //失败返回
        return FAILED;
    }
}
